package dev2dev.textclient;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

/**
 * Byte转换工具
 *
 * @author yangle
 */
public class ByteUtils {

    /**
     * 十六进制字符串转byte[]
     *
     * @param hex 十六进制字符串
     * @return byte[]
     */
    public static byte[] hexStr2Byte(String hex) {
        hex = hex.replace(" ", "");//去掉所有空格
        if (hex == null) {
            return new byte[]{};
        }

        // 奇数位补0
        if (hex.length() % 2 != 0) {
            hex = "0" + hex;
        }

        int length = hex.length();
        ByteBuffer buffer = ByteBuffer.allocate(length / 2);
        for (int i = 0; i < length; i++) {
            String hexStr = hex.charAt(i) + "";
            i++;
            hexStr += hex.charAt(i);
            byte b = (byte) Integer.parseInt(hexStr, 16);
            buffer.put(b);
        }
        return buffer.array();
    }

    /**
     * byte[]转十六进制字符串
     *
     * @param array byte[]
     * @return 十六进制字符串
     */
    public static String byteArrayToHexString(byte[] array) {
        if (array == null) {
            return "";
        }
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < array.length; i++) {
            buffer.append(byteToHex(array[i]) + " ");
        }
        return buffer.toString();
    }

    /**
     * byte转十六进制字符
     *
     * @param b byte
     * @return 十六进制字符
     */
    public static String byteToHex(byte b) {
        String hex = Integer.toHexString(b & 0xFF);
        if (hex.length() == 1) {
            hex = '0' + hex;
        }
        return hex.toUpperCase(Locale.getDefault());
    }


    /**
     * 字符串转换成为16进制(无需Unicode编码)
     *
     * @param str
     * @return
     */
    public static String str2HexStr(String str) {
        char[] chars = "0123456789ABCDEF".toCharArray();
        StringBuilder sb = new StringBuilder("");
        byte[] bs = str.getBytes();
        int bit;
        for (int i = 0; i < bs.length; i++) {
            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(chars[bit]);
            bit = bs[i] & 0x0f;
            sb.append(chars[bit]);
            // sb.append(' ');
        }
        return sb.toString().trim();
    }

    /**
     * 数字转16进制字符
     ***/
    public static String intToHex(int n) {
        StringBuffer s = new StringBuffer();
        String a;
        char[] b = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        while (n != 0) {
            s = s.append(b[n % 16]);
            n = n / 16;
        }
        a = s.reverse().toString();
        if (a.length() < 2) {
            a = "0" + a;
        }
        if (a.length()%2 ==1) {
            a = "0" + a;
        }
        return a;
    }

    //int 转 byte[]   低字节在前（低字节序）
    public static String toLH(int n) {
        byte[] b = new byte[2];
        b[0] = (byte) (n & 0xff);
        b[1] = (byte) (n >> 8 & 0xff);
//        b[2] = (byte) (n >> 16 & 0xff);
//        b[3] = (byte) (n >> 24 & 0xff);
        String str = ByteUtils.byteArrayToHexString(b);
        return str;
    }
    // byte[] 转 int 低字节在前（低字节序）
    public static int toInt(byte[] b){
        int res = 0;
        for(int i=0;i<b.length;i++){
            res += (b[i] & 0xff) << (i*8);
        }
        return res;
    }

    public static char[] getChars(byte[] bytes) {
        Charset cs = Charset.forName("UTF-8");
        ByteBuffer bb = ByteBuffer.allocate(bytes.length);
        bb.put(bytes);
        bb.flip();
        CharBuffer cb = cs.decode(bb);
        return cb.array();
    }

    /**
     * 将汉字转换车16进制字符串
     *
     * @param str
     * @return st
     */
    public static String enUnicode(String str) {// 将汉字转换为16进制数
        String st = "";
        try {
//这里要非常的注意,在将字符串转换成字节数组的时候一定要明确是什么格式的,这里使用的是gb2312格式的,还有utf-8,ISO-8859-1等格式
            byte[] by = str.getBytes("gb2312");
            for (int i = 0; i < by.length; i++) {
                String strs = Integer.toHexString(by[i]);
                if (strs.length() > 2) {
                    strs = strs.substring(strs.length() - 2);
                }
                st += strs;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return st;
    }


    // 转化十六进制编码为字符串汉字
    public static String toStringHex2(String s) {
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++) {
            try {
                baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(
                        i * 2, i * 2 + 2), 16));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            s = new String(baKeyword, "utf-8");// UTF-16le:Not
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return s;
    }

    /**
     *   String temp="94 01 00 00 60 10"; -->//10 60 00 00 01 94
     * java 十六进制 表示的字符串 怎么使他低字节在前，高字节在后
     * @return
     */
    public static String getstrhouhigh(String temp){
        List<String> list = Arrays.asList( temp.split(" "));
        Collections.reverse(list);

        StringBuffer stringBuffer = new StringBuffer();
        for(String string:list){
            stringBuffer.append(string);
            stringBuffer.append(" ");
        }
        temp = stringBuffer.toString();
        return temp;
    }


    public static void main(String[] args) {
//        String a ="313138";
//        String c = toStringHex2(a);
//        System.out.println(c);
//        String mun = "-118.151151";
//        Double du = Double.valueOf(mun);
//        System.out.println(du);

//        String a ="0135";
//        System.out.println(a.substring(2));
//        System.out.println(a.substring(2)+a.substring(0,2));
//        System.out.println(toLH(10));


        System.out.println(new String(hexStr2Byte("4D455353414745207369703A3332414543423233343333383031403139322E3136382E33312E3133303A33323431363B7472616E73706F72743D756470205349502F322E300D0A43616C6C2D49443A206662663166626565393834636234643463376562373231643330343133353864403139322E3136382E33312E3133300D0A435365713A2031204D4553534147450D0A46726F6D3A2022757365726E616D6522203C7369703A757365726E616D65403139322E3136382E33312E3133303A353036313E3B7461673D74657874636C69656E7476312E300D0A546F3A2022333241454342323334333338303122203C7369703A3332414543423233343333383031403139322E3136382E33312E3133303A33323431363E0D0A5669613A205349502F322E302F554450203139322E3136382E33312E3133303A353036313B6272616E63683D6272616E6368310D0A4D61782D466F7277617264733A2037300D0A436F6E746163743A2022757365726E616D6522203C7369703A757365726E616D65403139322E3136382E33312E3133303A353036313E0D0A436F6E74656E742D547970653A20746578742F706C61696E0D0A436F6E74656E742D4C656E6774683A20340D0A0D0A31313131")));


        byte[] audioData = {0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // V P X CC MM
                ,0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,

        }; // 假设这是要发送的音频数据

        // 添加RTC头部
        byte[] rtcHeader = {0x52, 0x54, 0x43}; // RTC头部标识
        byte[] rtcPacket = new byte[rtcHeader.length + audioData.length];
        System.arraycopy(rtcHeader, 0, rtcPacket, 0, rtcHeader.length);
        System.arraycopy(audioData, 0, rtcPacket, rtcHeader.length, audioData.length);
    }
}
